<?php

namespace App\Http\Form;

use App\Enums\BaseErrorCode;
use App\Enums\WorkOrder\ErrCode;
use App\Enums\WorkOrder\MissionEnum;
use App\Enums\WorkOrder\OrderEnum;
use App\Exceptions\Custom\CustomException;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Form\EleTakeaway\EleTakeawayForm;
use App\Http\Form\KfCashRegister\KfCashRegisterForm;
use App\Http\Form\KfCashRegister\KfCashRegisterFormAttribute;
use App\Http\Form\KfCashRegisterV2\KfCashRegisterV2Form;
use App\Http\Form\MeituanMerchantLink\MeituanMerchantLinkForm;
use App\Http\Form\MeituanTakeaway\MeituanTakeawayForm;
use App\Http\Form\TikTokBuildShop\TikTokBuildShopForm;
use App\Models\Appraise\AppraiseModel;
use App\Models\Common\ResourcesModel;
use App\Models\Cruise\CruiseShopLicenseResourceRecordsModel;
use App\Models\FuYou\WorkOrderFuyouInfoModel;
use App\Models\WorkOrder\WorkOrderApplyContentModel;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Models\WorkOrder\WorkOrderRejectDetailModel;
use App\Support\CustomForm\Attribute\AttributeSupport;
use App\Support\CustomForm\AttributeWorkOrderSupport;
use App\Support\Facade\CustomerValidator;
use App\Support\Singleton\SingletonInstance;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\Validator;


class Form extends SingletonInstance
{
    /**
     * @return array
     */
    public function getResourcesFields(): array
    {
        return collect((get_object_vars($this->getAttributeMap())))->map(function (AttributeSupport $attributeSupport) {
            if ($attributeSupport->getIsResources()) {
                return $attributeSupport->getInputName();
            }
            return "";
        })->values()->filter()->toArray();
    }


    /**
     * @param string $field
     * @param $value
     * @param array $extraParams
     * @param array $customAttributes
     * @param array $excludeRules
     * @return mixed
     * @throws ValidationException
     */
    public function validate(
        string $field,
        $value,
        array $extraParams = [],
        array $customAttributes = [],
        array $excludeRules = []
    ) {
        // TODO: Implement save() method.
        $this->{$field}->getValidateSupport()->validate(
            $field,
            $this->{$field}->getIsResources() && empty($value) ? "" : $value,
            $extraParams,
            array_merge([$this->{$field}->getInputName() => $this->{$field}->getInputDesc()], $customAttributes),
            $excludeRules
        );

        if ($handleValFunc = $this->{$field}->getHandleSaveValueFunc()) {
            $value = $handleValFunc($value);
        }
        return $value;
    }


    /**
     * @param int $parentType
     * @param int $type
     * @return Form|TikTokBuildShopForm
     */
    public static function getFormInstance(
        int $parentType,
        int $type,
        ?WorkOrderApplyMainModel $applyMainModel = null
    ): Form {
        if ($applyMainModel) {
            AttributeWorkOrderSupport::setApplyMainModel('', $applyMainModel);
        }

        switch ($parentType) {
            case OrderEnum::PROBLEM_PID_1:
                break;
            case OrderEnum::PROBLEM_PID_2:
                break;
            case OrderEnum::PROBLEM_PID_3:
                break;
            case OrderEnum::PROBLEM_PID_4:
                break;
            case OrderEnum::PROBLEM_PID_5:
                switch ($type) {
                    case OrderEnum::PROBLEM_PID_5_CHILDREN_100:
                        $form = KfCashRegisterForm::getInstance();
                        break;
                    case OrderEnum::PROBLEM_PID_5_CHILDREN_101:
                        $form = MeituanTakeawayForm::getInstance();
                        break;
                    case OrderEnum::PROBLEM_PID_5_CHILDREN_102:
                        $form = EleTakeawayForm::getInstance();
                        break;
                    case OrderEnum::PROBLEM_PID_5_CHILDREN_103:
                        $form = MeituanMerchantLinkForm::getInstance();
                        break;
                    case OrderEnum::PROBLEM_PID_5_CHILDREN_104:
                        $form = TikTokBuildShopForm::getInstance();
                        break;
                    case OrderEnum::PROBLEM_PID_5_CHILDREN_105:
                        $form = KfCashRegisterV2Form::getInstance();
                        break;
                    default:
                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "错误的表单类型 【{$type}】");
                        break;
                }
                break;
        }
        return $form;
    }

    /**
     * 根据门店id & 类型获取表单
     *
     * @param int $shopId
     * @param $parentType
     * @param int $type
     * @param int $uid
     * @return array
     * @throws GuzzleException
     */
    public static function getFormContentByShopIdAndType(int $shopId, $parentType, int $type, int $uid): array
    {
        $applyMainModel    = WorkOrderApplyMainModel::getOrCreateApplyMain($shopId, $parentType, $type, $uid);
        $applyContentModel = WorkOrderApplyContentModel::getOrCreateFunctionOpenApplyContent(
            $applyMainModel->workOrderNo,
            $uid,
            $shopId
        );

        $formInstance = self::getFormInstance($parentType, $type, $applyMainModel);
        $formContent  = new AnalysisFormContent($applyContentModel);

        $resources = ResourcesModel::getModuleBusinessResources(
            ResourcesModel::MODULE_TYPE_WORK_ORDER,
            ResourcesModel::BUSINESS_WORK_ORDER_FUNCTION_OPEN,
            $formContent->model->id,
            $formInstance->renderForm(collect([]))->getResourcesFields()
        );

        KfCashRegisterFormAttribute::$attributesMap = null;
        $formContent->mergeExtraContent((array)$resources);
//        if (empty($resources->businessLicenseImg) && empty($resources->foodBusinessLicenseImg)){
//            //拉数据门店证件备案数据，回显示
//            $licenseResourceData = CruiseShopLicenseResourceRecordsModel::getDataMappingFunctionOpen($shopId);
//            if ($licenseResourceData){
//                $formContent->mergeExtraContent($licenseResourceData);
//            }
//        }
        $formContentArr = $formInstance->renderForm(collect($formContent->getContent()))->getFormContent();
        $appraiseModel = AppraiseModel::getInfoByWorkOrderNo($applyMainModel->workOrderNo);//评价反馈详情

        // 夸父收银进件2.0 显示流程修改
        $status = WorkOrderApplyMainModel::applyMainStatus($applyMainModel->step);
        return [
            [
                "id"           => $applyContentModel->id,
                "status"       => $status,
                'childStep'    => $applyMainModel->childStep,
                "workOrderNo"  => $applyMainModel->workOrderNo,
                "step"         => $applyMainModel->step,
                "applyTime"    => formatDate($applyMainModel->createdAt->timestamp, ""),
                "finishTime"   => formatDate($applyMainModel->completeTime, ""),
                "formDesc"     => OrderEnum::FUNCTION_OPEN[$type],
                "formContent"  => $formContentArr,
                'appraiseId'   => $appraiseModel ? $appraiseModel->id : 0,
                'completeTime' => formatDate($applyMainModel->completeTime),
                "statusData"   => self::getStatusData($applyMainModel, $status),
            ],
            $formContent
        ];
    }


    /**
     * 根据申请主体模型 - 获取表单
     *
     * @param WorkOrderApplyMainModel $applyMainModel
     * @return array
     */
    public static function getFormContentByApplyMainModel(WorkOrderApplyMainModel $applyMainModel): array
    {
        $applyContentModel = $applyMainModel->contentRel;
        $formInstance      = self::getFormInstance(
            $applyMainModel->problemPid,
            $applyMainModel->problemChildId,
            $applyMainModel
        );
        $formContent       = new AnalysisFormContent($applyContentModel);

        $resources = ResourcesModel::getModuleBusinessResources(
            ResourcesModel::MODULE_TYPE_WORK_ORDER,
            ResourcesModel::BUSINESS_WORK_ORDER_FUNCTION_OPEN,
            $formContent->model->id,
            $formInstance->renderForm(collect())->getResourcesFields()
        );

        $formContent->mergeExtraContent((array)$resources);

        return [
            "id"          => $applyContentModel->id,
            "status"      => $applyMainModel->status,
            "formDesc"    => OrderEnum::FUNCTION_OPEN[$applyMainModel->problemChildId],
            "formContent" => $formInstance->renderForm($formContent->toCollection())->getFormContent()
        ];
    }


    /**
     * 表单单一字段保存 --- 废弃
     *
     * @param int $id
     * @param string $field
     * @param $value
     * @throws ValidationException
     * @throws Exception
     */
    public static function saveField(int $id, string $field, $value)
    {
        CustomerValidator::extend(
            'exclude_eq',
            function ($attribute, $value, $parameters, Validator $validator) {
                foreach ($parameters as $parameter) {
                    list($validateField, $validateFieldVal) = explode("-", $parameter);
                    $validateFieldNowValue = $validator->getData()["$validateField"] ?? "";
                    if (strlen($validateFieldNowValue) == 0 || $validateFieldNowValue != $validateFieldVal) {
                        return false;
                    }
                }

                return true;
            }, "当前状态暂不支持修改 【:attribute】 字段");

        $applyContent = WorkOrderApplyContentModel::query()->where("id", $id)->first();
        $formInstance = self::getFormInstance(
            $applyContent->applyMainRel->problemPid,
            $applyContent->applyMainRel->problemChildId,
        );
        $formContent  = new AnalysisFormContent($applyContent);
        $resources    = ResourcesModel::getModuleBusinessResources(
            ResourcesModel::MODULE_TYPE_WORK_ORDER,
            ResourcesModel::BUSINESS_WORK_ORDER_FUNCTION_OPEN,
            $formContent->model->id,
            $formInstance->renderForm(collect())->getResourcesFields()
        );

        $formContent->mergeExtraContent((array)$resources);
        $formInstance->renderForm($formContent->toCollection());
        $validatedValue = $formInstance->validate($field, $value, $formContent->getContent());


        if ($formInstance->{$field}->getIsResources()) {
            ResourcesModel::moduleBusinessSingleResourcesUpdate(
                ResourcesModel::MODULE_TYPE_WORK_ORDER,
                ResourcesModel::BUSINESS_WORK_ORDER_FUNCTION_OPEN,
                $field,
                $applyContent->id,
                (array)$validatedValue,
                in_array($field, ResourcesModel::$privateResourcesFields) ? 0 : 1
            );
        } else {
            $formContent->saveField($field, $validatedValue);
        }

        $applyMain = WorkOrderApplyMainModel::query()
                                            ->where("workOrderNo", $applyContent->workOrderNo)
                                            ->first();

        if (in_array($applyMain->problemChildId, array_keys(OrderEnum::FUNCTION_OPEN))) {
            WorkOrderApplyMainModel::query()
                                   ->where('shopId', $applyMain->shopId)
                                   ->where("status", OrderEnum::MAIN_STATUS_ING)
                                   ->whereIn(
                                       "problemChildId",
                                       collect(OrderEnum::FUNCTION_OPEN)
                                           ->except([$applyMain->problemChildId])->keys()->toArray()
                                   )->get()
                                   ->each(function (WorkOrderApplyMainModel $applyMainModel) use (
                                       $field,
                                       $validatedValue,
                                       $formInstance
                                   ) {
                                       $applyContent = $applyMainModel->contentRel;
                                       if ($formInstance->{$field}->getIsResources()) {
                                           ResourcesModel::moduleBusinessSingleResourcesUpdate(
                                               ResourcesModel::MODULE_TYPE_WORK_ORDER,
                                               ResourcesModel::BUSINESS_WORK_ORDER_FUNCTION_OPEN,
                                               $field,
                                               $applyContent->id,
                                               (array)$validatedValue,
                                               in_array($field, ResourcesModel::$privateResourcesFields) ? 0 : 1
                                           );
                                       } else {
                                           $formContent = new AnalysisFormContent($applyContent);
                                           $formContent->saveField($field, $validatedValue);
                                       }
                                   });
        }
    }


    /**
     * 表单多字段保存
     *
     * @param int $id
     * @param array $fields
     * @return array
     * @throws Exception
     */
    public static function saveFields(int $id, array $fields): array
    {
        CustomerValidator::extend(
            'exclude_eq',
            function ($attribute, $value, $parameters, Validator $validator) {
                $actuallyParams = unserialize($parameters[0]);
                $validateRes = false;
                foreach ($actuallyParams as $parentParams){
                    $tempValidateRes = true;
                    foreach ($parentParams as $field=> $fieldValue){
                        $fieldNowValue = $validator->getData()[$field] ?? "";
                        if($fieldNowValue != $fieldValue){
                            $tempValidateRes = false;
                        }
                    }
                    if($tempValidateRes){
                        $validateRes = true;
                        break;
                    }
                }
                return $validateRes;
            }, "当前状态暂不支持修改 【:attribute】 字段");

        $applyContent = WorkOrderApplyContentModel::query()->where("id", $id)->first();
        $formInstance = self::getFormInstance(
            $applyContent->applyMainRel->problemPid,
            $applyContent->applyMainRel->problemChildId
        );
        $formInstance->renderForm(collect());
        $inputNames = [];
        /** @var AttributeSupport $attr */
        foreach ($formInstance->getAttributeMap() as $attr){
            $inputNames[] = $attr->getInputName();
        }

        $validateErrorFields = [];
        try {
            DB::beginTransaction();
            $applyContent = WorkOrderApplyContentModel::query()->where("id", $id)->lockForUpdate()->first();
            $params       = WorkOrderApplyContentModel::getContent($applyContent, $fields)->toArray();
            $resources    = $content = [];
            collect($fields)->filter(function ($validateVal, string $fieldName) use ($inputNames) {
                return in_array($fieldName, $inputNames);
            })->each(function ($validateVal, string $fieldName) use (
                $formInstance,
                $params,
                &$resources,
                &$content,
                &$validateErrorFields
            ) {
                //根据收款类型进行判断  对公&对私

                //1. 对私情况   身份证  收款人  夸父授权书   （营业执照）
                //2. 对公情况   夸父授权书    营业执照

                $attribute = $formInstance->{$fieldName};
                try {
                    $validatedValue = $formInstance->validate($fieldName, $validateVal, (array)$params, [], ["ExcludeEq"]);

                    if ($attribute->getIsResources()) {
                        $resources = array_merge($resources, [$fieldName => $validatedValue]);
                    } else {
                        $content = array_merge($content, [$fieldName => $validatedValue]);
                    }
                } catch (ValidationException $validationException) {
                    $field  = current(array_keys($validationException->validator->errors()->getMessages()));
                    $errMsg = implode(",", current($validationException->validator->errors()->getMessages()));
                    array_push($validateErrorFields,
                        $formInstance->getAttributeMap()->{$field}->setErrMsg($errMsg)->build());
                }
            });

            if ($validateErrorFields){
                throw new CustomException();
            }

            ResourcesModel::moduleBusinessResourcesCustomFieldsUpdate(
                $resources,
                ResourcesModel::MODULE_TYPE_WORK_ORDER,
                ResourcesModel::BUSINESS_WORK_ORDER_FUNCTION_OPEN,
                $id
            );

            WorkOrderApplyContentModel::updateContent($applyContent, $content);

            if (in_array($applyContent->applyMainRel->problemChildId, array_keys(OrderEnum::FUNCTION_OPEN))) {
                WorkOrderApplyMainModel::query()
                                       ->where('shopId', $applyContent->applyMainRel->shopId)
                                       ->where("status", OrderEnum::MAIN_STATUS_ING)
                                       ->whereIn(
                                           "problemChildId",
                                           collect(OrderEnum::FUNCTION_OPEN)
                                               ->except([$applyContent->applyMainRel->problemChildId])->keys()
                                               ->toArray()
                                       )->get()
                                       ->each(
                                           function (WorkOrderApplyMainModel $applyMainModel) use (
                                               $content,
                                               $resources,
                                               $formInstance
                                           ) {
                                               $applyContent = $applyMainModel->contentRel;
                                               ResourcesModel::moduleBusinessResourcesCustomFieldsUpdate(
                                                   $resources,
                                                   ResourcesModel::MODULE_TYPE_WORK_ORDER,
                                                   ResourcesModel::BUSINESS_WORK_ORDER_FUNCTION_OPEN,
                                                   $applyContent->id
                                               );

                                               WorkOrderApplyContentModel::updateContent($applyContent, $content);
                                           });
            }

            // 删除被驳回的内容（有的话）
            $workOrderNo = WorkOrderApplyContentModel::query()->where('id', $id)->value('workOrderNo') ?? 0;
            WorkOrderRejectDetailModel::delData($workOrderNo, array_keys($fields));

            DB::commit();
        } catch (CustomException $customException){
          DB::rollBack();
          return $validateErrorFields;
        } catch (Exception $exception) {
            DB::rollBack();
            throw $exception;
        }
        return [];
    }

    /**
     * 通过 id 提交表单
     *
     * @param int $id
     * @return array
     */
    public static function submitFormById(int $id): array
    {
        $validateErrorFields = [];
        $applyContent        = WorkOrderApplyContentModel::query()->where("id", $id)->first();

        $formInstance = self::getFormInstance(
            $applyContent->applyMainRel->problemPid,
            $applyContent->applyMainRel->problemChildId
        );
        $formContent  = new AnalysisFormContent($applyContent);
        $resources    = ResourcesModel::getModuleBusinessResources(
            ResourcesModel::MODULE_TYPE_WORK_ORDER,
            ResourcesModel::BUSINESS_WORK_ORDER_FUNCTION_OPEN,
            $formContent->model->id,
            $formInstance->renderForm(collect([]))->getResourcesFields()
        );

        $formContent->mergeExtraContent((array)$resources);
        $formInstance->renderForm($formContent->toCollection());

//        CustomerValidator::extend(
//            'exclude_eq',
//            function ($attribute, $value, $parameters, Validator $validator) {
//                foreach ($parameters as $parameter) {
//                    list($validateField, $validateFieldVal) = explode("-", $parameter);
//                    $validateFieldNowValue = $validator->getData()["$validateField"] ?? "";
//                    if (strlen($validateFieldNowValue) == 0 || $validateFieldNowValue != $validateFieldVal) {
//                        return false;
//                    }
//                }
//
//                return true;
//            }, "当前状态暂不支持修改 【:attribute】 字段");

        CustomerValidator::extend(
            'exclude_eq',
            function ($attribute, $value, $parameters, Validator $validator) {
                $actuallyParams = unserialize($parameters[0]);
                $validateRes = false;
                foreach ($actuallyParams as $parentParams){
                    $tempValidateRes = true;
                    foreach ($parentParams as $field=> $fieldValue){
                        $fieldNowValue = $validator->getData()[$field] ?? "";
                        if($fieldNowValue != $fieldValue){
                            $tempValidateRes = false;
                        }
                    }
                    if($tempValidateRes){
                        $validateRes = true;
                        break;
                    }
                }
                return $validateRes;
            }, "当前状态暂不支持修改 【:attribute】 字段");

        collect($formInstance->getAttributeMap())
            ->each(function (FormAttribute $attribute) use (
                $formContent,
                &$validateErrorFields,
                $formInstance
            ) {
                $fieldName   = $attribute->getInputName();
                $validateVal = $formContent->getField($fieldName);
                try {
                    $formInstance->validate(
                        $fieldName,
                        $validateVal,
                        $formContent->getContent(),
                        [],
                        ["ExcludeEq"]
                    );
                } catch (ValidationException $validationException) {
                    $errMsg = implode(",", current($validationException->validator->errors()->getMessages()));
                    array_push($validateErrorFields,
                        $attribute->setErrMsg($errMsg)->build());
                } catch (Exception $exception) {
                    Log::error("【工单表单验证失败】【{$exception->getMessage()}】");
                }
            });

        return [$applyContent,$resources,  $validateErrorFields];

    }

    /**
     * 全量修改form content
     *
     * @param string $workOrderNo
     * @param object $params
     * @return array
     */
    public static function submitFormByCompleteFields(string $workOrderNo, object $params): array
    {
        $validateErrorFields = [];
        $requestParams       = collect($params);
        $applyContent        = WorkOrderApplyContentModel::query()->where("workOrderNo", $workOrderNo)->first();
        $formInstance        = self::getFormInstance(
            $applyContent->applyMainRel->problemPid,
            $applyContent->applyMainRel->problemChildId
        );
        $formInstance->renderForm(new Collection());

        if ($applyContent->applyMainRel->step >= MissionEnum::STEP_99) {//工单任务完成前，都可以编辑工单的信息
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_STEP_NORMAL_OFF));
        }
//        CustomerValidator::extend(
//            'exclude_eq',
//            function ($attribute, $value, $parameters, Validator $validator) {
//                foreach ($parameters as $parameter) {
//                    list($validateField, $validateFieldVal) = explode("-", $parameter);
//                    $validateFieldNowValue = $validator->getData()["$validateField"] ?? "";
//                    if (strlen($validateFieldNowValue) == 0 || $validateFieldNowValue != $validateFieldVal) {
//                        return false;
//                    }
//                }
//
//                return true;
//            }, "当前状态暂不支持修改 【:attribute】 字段");

        CustomerValidator::extend(
            'exclude_eq',
            function ($attribute, $value, $parameters, Validator $validator) {
                $actuallyParams = unserialize($parameters[0]);
                $validateRes = false;
                foreach ($actuallyParams as $parentParams){
                    $tempValidateRes = true;
                    foreach ($parentParams as $field=> $fieldValue){
                        $fieldNowValue = $validator->getData()[$field] ?? "";
                        if($fieldNowValue != $fieldValue){
                            $tempValidateRes = false;
                        }
                    }
                    if($tempValidateRes){
                        $validateRes = true;
                        break;
                    }
                }
                return $validateRes;
            }, "当前状态暂不支持修改 【:attribute】 字段");

        $resources = $content = [];
        collect($formInstance->getAttributeMap())
            ->each(function (FormAttribute $attribute) use (
                $requestParams,
                $params,
                $formInstance,
                &$resources,
                &$content,
                &$validateErrorFields
            ) {
                try {
                    $fieldName   = $attribute->getInputName();
                    $validateVal = $requestParams->get($fieldName, $attribute->defaultVal);

                    $validatedVal = $formInstance->validate($fieldName, $validateVal, (array)$params, [],
                        ["ExcludeEq"]);

                    if ($formInstance->{$fieldName}->getIsResources()) {
                        $resources = array_merge($resources, [$fieldName => $validatedVal]);
                    } else {
                        $content = array_merge($content, [$fieldName => $validatedVal]);
                    }
                } catch (ValidationException $validationException) {
                    $field  = current(array_keys($validationException->validator->errors()->getMessages()));
                    $errMsg = implode(",", current($validationException->validator->errors()->getMessages()));
                    array_push($validateErrorFields,
                        $formInstance->getAttributeMap()->{$field}->setErrMsg($errMsg)->build());
                }
            });

        if (empty($validateErrorFields)) {
            ResourcesModel::moduleBusinessResourcesUpdate(
                $resources,
                ResourcesModel::MODULE_TYPE_WORK_ORDER,
                ResourcesModel::BUSINESS_WORK_ORDER_FUNCTION_OPEN,
                $applyContent->id,
            );

            WorkOrderApplyContentModel::updateContent($applyContent, $content);

            $applyMain = $applyContent->applyMainRel;
            if (in_array($applyMain->problemChildId, array_keys(OrderEnum::FUNCTION_OPEN))) {
                //同步数据
                WorkOrderApplyMainModel::query()
                                       ->where('shopId', $applyMain->shopId)
                                       ->where("status", OrderEnum::MAIN_STATUS_ING)
                                       ->whereIn(
                                           "problemChildId",
                                           collect(OrderEnum::FUNCTION_OPEN)
                                               ->except($applyMain->problemChildId)
                                               ->keys()
                                               ->toArray()
                                       )->get()
                                       ->each(function (WorkOrderApplyMainModel $applyMainModel) use (
                                           $resources,
                                           $content
                                       ) {
                                           ResourcesModel::moduleBusinessResourcesUpdate(
                                               $resources,
                                               ResourcesModel::MODULE_TYPE_WORK_ORDER,
                                               ResourcesModel::BUSINESS_WORK_ORDER_FUNCTION_OPEN,
                                               $applyMainModel->contentRel->id,
                                           );

                                           WorkOrderApplyContentModel::updateContent($applyMainModel->contentRel,
                                               $content);
                                       });
            }

        }

        return $validateErrorFields;
    }

    /**
     * @param $name
     * @return AttributeSupport
     */
    public function __get($name)
    {
        // TODO: Implement __get() method.
        return FormAttribute::$attributesMap->{$name};
    }

    /**
     * 转化工单流程状态
     * @param WorkOrderApplyMainModel|null $applyMain
     * @param int $status
     * @param string $workOrderNo
     * @return array
     */
    public static function getStatusData(?WorkOrderApplyMainModel $applyMain = null, int $status, string $workOrderNo = ''): array
    {
        if ($workOrderNo && !$applyMain) {
            $applyMain = WorkOrderApplyMainModel::query()->where('workOrderNo', $workOrderNo)->first();
        }
        if ($applyMain && $applyMain->problemPid == OrderEnum::PROBLEM_PID_5 && $applyMain->problemChildId == OrderEnum::PROBLEM_PID_5_CHILDREN_105) {
            $statusData = [
                [
                    'title' => '提交成功',
                    'desc'  => '',
                ],
                [
                    'title' => '商家待认证',
                    'desc'  => '',
                ],
                [
                    'title' => '系统对接中',
                    'desc'  => '',
                ],
                [
                    'title' => '已开通',
                    'desc'  => '',
                ],
            ];// 兼容前端显示
            if ($status == OrderEnum::MAIN_STATUS_ING) {// 原申请中 拆分-审核中，商家待认证，系统对接中
                $fuyouInfo             = WorkOrderFuyouInfoModel::getInfoByWorkOrderNo($applyMain->workOrderNo);
                $fuyouStep             = $fuyouInfo['step'] ?? 0;
                $weChatAuthorizeStatus = $fuyouInfo['weChatAuthorizeStatus'] ?? 0;//微信授权状态 0待认证 1成功
                $alipayAuthorizeStatus = $fuyouInfo['alipayAuthorizeStatus'] ?? 0;//支付宝授权状态 0待认证 1成功
                switch ($fuyouStep) {
                    case WorkOrderFuyouInfoModel::DEFAULT_STEP_BUSINESS_AUTHENTICATION;//商家待认证
                    case WorkOrderFuyouInfoModel::DEFAULT_STEP_EMAIL_MCH_NAME_PASSWORD;//系统对接中
                        if ($weChatAuthorizeStatus == 1 && $alipayAuthorizeStatus == 1) {//微信授权状态&支付宝授权状态 成功才显示下一步
                            $status = OrderEnum::MAIN_STATUS_FINISH;
                        } else {
                            $status = OrderEnum::MAIN_STATUS_ING;
                        }
                        break;
                }
                $statusData[$status]['status'] = 1;
            } elseif ($status == OrderEnum::MAIN_STATUS_FINISH) {
                $statusData[3]['status'] = 1;
            }
        } else {
            $statusData                    = [
                [
                    'title' => '提交成功',
                    'desc'  => '',
                ],
                [
                    'title' => '申请中',
                    'desc'  => '',
                ],
                [
                    'title' => '已开通',
                    'desc'  => '',
                ],
            ];
            $statusData[$status]['status'] = 1;
        }
        return $statusData;
    }
}
